package com.cs.redis;

import com.cs.redis.mapper.UserMapper;
import com.cs.redis.model.User;
import com.cs.redis.receive.Receiver;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@MapperScan(basePackages = {"com.cs.redis.mapper"})
@RestController
@EnableEurekaClient
@SpringBootApplication
public class RedisApplication {

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("topic"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        //指定Receiver为代理接收类,接收消息方法为receiveMessage
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver() {
        return new Receiver();
    }

    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping(value = "/sendRedisMessage")
    public void sendRedisMessage(String message) {
        stringRedisTemplate.convertAndSend("topic", message);
    }

    @Resource
    RedisTemplate<String, User> redisTemplate;

    @Autowired
    UserMapper userMapper;

    @GetMapping(value = "/getUserById")
    public User getUserById(Integer id) {
        String key = "user_" + id;
        //缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            User user = redisTemplate.opsForValue().get(key);
            System.out.println("从缓存中读取了数据");
            return user;
        }
        //从数据库读取，并存到缓存
        User user = userMapper.selectByPrimaryKey(id);
        //放入缓存，并设置缓存时间
        redisTemplate.opsForValue().set(key, user, 10, TimeUnit.SECONDS);
        return user;
    }

}
